package com.flutter_ecg.flutter_ecg.ecgapplication.ecgrealtimecheck;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
//import android.support.v7.app.AlertDialog;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
//import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import com.ikinloop.iklibecgcheck.IIKEcgCheckEndEvent;
import com.ikinloop.iklibecgcheck.IIKEcgDataEvent;
import com.ikinloop.iklibecgcheck.IIKEcgDeviceNoWhiteListEvent;
import com.ikinloop.iklibecgcheck.IIKEcgStateEvent;
import com.ikinloop.iklibecgcheck.IKEcgCheck;
import com.flutter_ecg.flutter_ecg.R;
import com.flutter_ecg.flutter_ecg.ecgapplication.IKEcgCheckInterface;
import com.flutter_ecg.flutter_ecg.ecgapplication.ecgdevicescan.ECGDeviceScanActivity;
import com.flutter_ecg.flutter_ecg.ecgapplication.utils.BleAssistUtil;
import com.flutter_ecg.flutter_ecg.ecgapplication.utils.Constants;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import static com.flutter_ecg.flutter_ecg.ecgapplication.utils.Constants.ECGDEVICEID_KEY_NAME;
import static com.flutter_ecg.flutter_ecg.ecgapplication.utils.Constants.SP_ECGDEVICEID_NAME;
import com.flutter_ecg.flutter_ecg.MainActivity;

import org.json.JSONObject;

import java.io.Serializable;
import java.util.HashMap;

/*
    该页面类实现了心电图的实时检测功能。
    流程描述：    当启动该页面后，系统会根据之前绑定的心电设备，自动连接设备。当用户打开心电设备电源开关后，心电
             设备将自动被手机连接，此时用户双手轻轻按压心电仪电极片，系统会采集到心电信号，并在该页面上实时绘
             制心电图。在此过程中，并伴有各种异常的声音提示。
                当检测完成后，该页面会调用EcgResultActivity启动心电分析结果的显示页面，并停止蓝牙传输。

 */
public class EcgCheckActivity extends AppCompatActivity implements IIKEcgCheckEndEvent, IIKEcgStateEvent, IIKEcgDataEvent, IIKEcgDeviceNoWhiteListEvent {

    private static final String TAG = EcgCheckActivity.class.getSimpleName();

    private IKEcgCheck ikEcgCheck;

    private IKEcgCheckLayout ikEcgCheckLayout;
    private TextView unBindDeviceBtn;
    private int duration;//检测总时长
    private String deviceid = "";
    private Boolean isException = false; //信号干扰大,异常

    private PowerManager.WakeLock m_wakeLockObj = null;
    private PowerManager pm;

    private IKEcgCheckInterface ikEcgCheckInterface;

    private boolean isResumed = false;
    private boolean isPlayedVoice = false;//播放检测开始声音标识
    private boolean isChecking = false;//是否开始检测

    private AlertDialog newDeviceDialog;

    private String customData;

    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (!isResumed) {
                return;
            }
            switch (msg.what) {
                case 20001://系统蓝牙未打开
                    ikEcgCheckLayout.hintOpenBle();
                    ikEcgCheck.IKStopEcgCheck();
                    break;
                case 20002://系统蓝牙打开
                    startEcgCheck();
                    break;
                case 20007://连接成功
                    isChecking = true;
                    isException = false;
                    ikEcgCheckLayout.hintTouchMetal();
                    break;
                case 20008://蓝牙连接断开
                    isChecking = false;
                    if (!isException) {
                        resetCheckState();
                    }
                    break;
                case 20009://蓝牙连接异常
                    isChecking = false;
                    resetCheckState();
                    break;
                case 20010://电池电量
                    int bettery = 100;
                    try {
                        bettery = Integer.valueOf((String) msg.obj);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                        break;
                    }
                    if (bettery < 35) {
                        ikEcgCheckLayout.hintLowPower();
                    }
                    break;
                case 30001://实时心率
                    ikEcgCheckLayout.setHeartRate((String) msg.obj);
                    break;
                case 30002://干扰大
                    String value = (String) msg.obj;
                    if ("1".equalsIgnoreCase(value)) {
                        ikEcgCheckLayout.hintTooBigNoise();
                    } else if ("2".equalsIgnoreCase(value)) {
                        ikEcgCheckLayout.hintDetecting();
                    }
                    break;
                case 30003://检测时间
                    int time = Integer.valueOf((String) msg.obj);
                    if (duration < time) {
                        return;
                    }
                    ikEcgCheckLayout.setDetectTime(duration - time + 1);//算法回调中的时间为40->1
                    break;
                case 30004://干扰大，数据不可用
                    isChecking = false;
                    isException = true;
                    ikEcgCheckLayout.hintNoiseBigTestAgain();
                    removeMessages(0x01);
                    sendEmptyMessageDelayed(0x01, 5000);
//                    resetCheckState();
                    break;
                case 0x01:
                    isChecking = false;
                    isException = false;
                    resetCheckState();
                    break;
                default:
                    //其他事件暂不做处理
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_ecg_check);
        pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        ikEcgCheckInterface = (IKEcgCheckInterface) getIntent().getSerializableExtra(Constants.IKECGINTERFACE_KEY);
        customData = getIntent().getStringExtra(Constants.CUSTOMDATA_KEY);
        initView();
//        initIKEcgLib();
        initBondDeviceInfo();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!BleAssistUtil.isLocServiceEnable(this)) {
            BleAssistUtil.openLocService(this, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    finish();
                }
            });
        } else {
            isResumed = true;
            initIKEcgLib();
            ikEcgCheckLayout.setHeartRate("00");
            ikEcgCheckLayout.IKEcgViewReset();
            startEcgCheck();
            acquireWakeLock();
        }
    }
    @Override
    protected void onPause() {
        Log.d(TAG,"onPause");
        super.onPause();
        isResumed = false;
        handler.removeMessages(0x01);
        if (ikEcgCheck != null) {
            ikEcgCheck.IKStopEcgCheck();
            ikEcgCheck.IKUninit();
            ikEcgCheck = null;
        }
        releaseWakeLock();
        if (ikEcgCheckLayout != null) {
            ikEcgCheckLayout.stopVoice();
        }
        isChecking = false;
        if (null != newDeviceDialog && newDeviceDialog.isShowing()) {
            newDeviceDialog.dismiss();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        Log.d(TAG,"onDestroy");
        super.onDestroy();
        ikEcgCheckLayout.stopVoice();
        if (ikEcgCheck != null) {
            ikEcgCheck.IKStopEcgCheck();
            ikEcgCheck.IKUninit();
            ikEcgCheck = null;
        }
    }

    private void startEcgCheck() {
        if(null == ikEcgCheck){
            return;
        }
        SharedPreferences sharedPreferences = getSharedPreferences(SP_ECGDEVICEID_NAME, Context.MODE_PRIVATE);
        deviceid = sharedPreferences.getString(ECGDEVICEID_KEY_NAME, "");
        ikEcgCheckLayout.hintPressPowerBtn();
        ikEcgCheck.IKSetEcgDeviceId(deviceid);
        String userInfo = null;
        try {
//            userInfo = ikEcgCheckInterface.createEcgUserInfo(customData);
            userInfo = createEcgUserInfo(customData);
        } catch (Exception e) {
            e.printStackTrace();
            Log.i("Exception:::::", "userInfo is null:::::" + e.toString());
            return;
        }
        if (TextUtils.isEmpty(userInfo)) {
            Log.i("用户信息为空============", "");
            return;
        }
        ikEcgCheck.IKStartEcgCheck(createEcgUserInfo(customData), IKEcgCheck.EcgDetectTime.DetectTime40S);
        duration = 40;
        ikEcgCheckLayout.setMaxTime(duration);//需与IKStartEcgCheck第二个参数设置的检测时间一致
    }

    private void resetCheckState(){
        isPlayedVoice = false;
        ikEcgCheckLayout.setHeartRate("00");
        ikEcgCheckLayout.IKEcgViewReset();
//        if(ikEcgCheck != null){
//            ikEcgCheck.IKStopEcgCheck();
//        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        startEcgCheck();
    }

    private void initView() {
        ikEcgCheckLayout = (IKEcgCheckLayout) findViewById(R.id.ecg_check_layout);
        ikEcgCheckLayout.initEcgCheckLayout(this);
        unBindDeviceBtn = (TextView) findViewById(R.id.unbind_device_btn);
        unBindDeviceBtn.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        unBindDeviceBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isChecking) {
                    Toast.makeText(EcgCheckActivity.this, R.string.string_detecting, Toast.LENGTH_SHORT).show();
                    return;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(EcgCheckActivity.this);
                builder.setMessage(R.string.string_unbind_device_confirm_title);
                builder.setNegativeButton(R.string.string_unbind_device_confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        SharedPreferences sharedPreferences = getSharedPreferences(SP_ECGDEVICEID_NAME, Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putString(ECGDEVICEID_KEY_NAME, "").commit();
                        Intent intent = new Intent(EcgCheckActivity.this, ECGDeviceScanActivity.class);
                        intent.putExtra(Constants.IKECGINTERFACE_KEY, ikEcgCheckInterface);
                        intent.putExtra(Constants.CUSTOMDATA_KEY, customData);
                        startActivity(intent);
                        finish();
                    }
                }).setPositiveButton(R.string.string_unbind_device_cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create().show();
            }
        });
        ikEcgCheckLayout.setBackClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(EcgCheckActivity.this, MainActivity.class));
                finish();
            }
        });
    }

    /**
     * Initialization ikEcgCheck
     */
    private void initIKEcgLib() {
        if (null == ikEcgCheck) {
            ikEcgCheck = ikEcgCheck.getInstance(EcgCheckActivity.this);

            ikEcgCheck.IKRegistEcgCheckEndEvent(this, null);
            ikEcgCheck.IKRegistEcgStateEvent(this, null);
            ikEcgCheck.IKRegistEcgDataEvent(this);
            ikEcgCheck.IKRegistEcgDeviceNoWhiteListEvent(this);
            ikEcgCheck.IKInit();
//            String name = getApplicationContext().getExternalFilesDir(null).getAbsolutePath();
//            Log.i(TAG, "name::::" + name);
//            ikEcgCheck.IKSetEcgDataPath(name + File.separator + "ecg");
        }
    }

    private void initBondDeviceInfo() {
        SharedPreferences sharedPreferences = this.getSharedPreferences(SP_ECGDEVICEID_NAME, Context.MODE_PRIVATE);
        deviceid = sharedPreferences.getString(ECGDEVICEID_KEY_NAME, "");
    }



    @Override
    public void OnReciveEcgState(int i, String s, Object o) {
        Log.i(TAG, "------>OnReciveEcgState<------ common=" + i + " content=" + s);
        Message msg = handler.obtainMessage();
        msg.what = i;
        msg.obj = s;
        handler.sendMessage(msg);
    }

    @Override
    public void OnReciveEcgData(final int ecgData) {
//        Log.i(TAG, "------>OnRecivEcgData<------ ecgdata=" + ecgData);
        if (!isResumed) {
            return;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!isPlayedVoice) {
                    ikEcgCheckLayout.playCheckStart();
                    isPlayedVoice = true;
                }
                ikEcgCheckLayout.drawEcgData(ecgData);
            }
        });
    }

    @Override
    public void OnEcgDeviceNoWhiteListEvent(String s) {
        if (!isResumed) {
            return;
        }
        Log.i(TAG, "------>OnEcgDeviceNoWhiteListEvent<------ " + s);
//        handler.sendEmptyMessage(MSG_NO_WHITELIST_EVENT);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
//                if (null != ikEcgCheck) {
//                    resetCheckState();
//                }
                releaseWakeLock();
                ikEcgCheckLayout.hintFindNotBoundDevice();
                if (ikEcgCheck != null) {
                    ikEcgCheck.IKStopEcgCheck();
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(EcgCheckActivity.this);
                builder.setMessage(R.string.string_found_new_device);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });

                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            dialog.dismiss();
                            resetCheckState();
                        }
                    });
                newDeviceDialog = builder.create();
                newDeviceDialog.show();
//                    Toast.makeText(EcgCheckActivity.this, R.string.string_found_not_bond_device, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void OnEcgCheckEnd(Object o) {
        Log.i(TAG, "------>OnEcgCheckEnd<------");
        if (!isResumed) {
            return;
        }
        if (ikEcgCheckLayout != null) {
            ikEcgCheckLayout.playCheckEnd();
        }
        if(isException){
            return;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(EcgCheckActivity.this, "EcgDetect over!", Toast.LENGTH_SHORT).show();
            }
        });

        if (ikEcgCheck != null) {
            final String result = ikEcgCheck.IKGetCurrEcgSmartResult();
            String tarFileName = ikEcgCheck.IKGetCurrEcgDataFilePath();
            if (TextUtils.isEmpty(result) || TextUtils.isEmpty(tarFileName)) {
                return;
            }
            //todo result中hrmean为空或者为0的时候直接返回。
            JSONObject ecgSmartResultObj = null;
            try {
                ecgSmartResultObj = new JSONObject(result);
                JSONObject ecgValObj = ecgSmartResultObj.getJSONObject("ecgval");
                String hrmean = ecgValObj.getString("hrmean");
                if (TextUtils.isEmpty(hrmean) || hrmean.startsWith("0")) {
                    return;
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Log.i(TAG, e.toString());
            }
            try {
//                ikEcgCheckInterface.saveEcgResult(result, tarFileName, ikEcgCheckInterface.createEcgUserInfo(customData), customData);
                Log.i("检测结束======================", result);
                saveEcgResult(result, tarFileName, createEcgUserInfo(customData), customData);
            } catch (Exception e) {
                e.printStackTrace();
                Log.i(TAG, e.toString());
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(EcgCheckActivity.this, EcgResultActivity.class);
                    intent.putExtra(Constants.ECGRESMARTSULT_KEY, result);
                    startActivity(intent);
                }
            });
        }

    }

    public void releaseWakeLock() {
        if (m_wakeLockObj != null && m_wakeLockObj.isHeld()) {
            m_wakeLockObj.release();
            m_wakeLockObj = null;
        }
    }

    public void acquireWakeLock() {
        if (m_wakeLockObj == null) {
            m_wakeLockObj = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, TAG);
            m_wakeLockObj.acquire();
        }
    }
    private String createEcgUserInfo(String customData) {
        //todo 以下代码为模拟读取用户信息代码。可对此代码进行删除修改。
        //todo 如可以从自己的后台系统读取用户数据。
        HashMap<String, String> userInfoMap = new HashMap<>();
        userInfoMap.put("ssname", "San");
        userInfoMap.put("gender", "10000");
        userInfoMap.put("birth", "1988-01-01");
        userInfoMap.put("height", "182");
        userInfoMap.put("weight", "77");
        JSONObject userInfo = new JSONObject(userInfoMap);
        return userInfo.toString();
    }
    private void saveEcgResult(String ecgSmartResult, String tarFilePath, String userInfo, String userData) {
        Log.i("调用saveEcgResult==============", ecgSmartResult);
        runOnUiThread(new Runnable() {
            public void run() {
                MainActivity.sendData(ecgSmartResult, tarFilePath, userInfo, userData);
            }
        });
    }
}
